package com.tl.web04.service;

import com.alibaba.fastjson.JSONObject;
import com.tl.web04.config.Config;
import com.tl.web04.constant.CodeEnum;
import com.tl.web04.constant.ResponseResult;
import com.tl.web04.model.entity.User;
import com.tl.web04.utils.StringUtil;

import javax.servlet.ServletContext;
import java.util.HashMap;

public class LoginAndRegisterService {
    //登录的方法
    public static ResponseResult login(HashMap<String, User> map, String username, String password) {
        String msg = "";
        Integer code = 0;
        JSONObject jsonObject = null;
        //非空校验
        if (StringUtil.notNullVerify(username) || StringUtil.notNullVerify(username)) {
            msg = CodeEnum.USERNAME_OR_PASSWORD_IS_EMPTY.getMsg();
            code = CodeEnum.USERNAME_OR_PASSWORD_IS_EMPTY.getCode();
        }else{
            //查询map中是否有该用户
            if(map.get(username)==null){
                msg = CodeEnum.NOT_REGISTERED.getMsg();
                code = CodeEnum.NOT_REGISTERED.getCode();
            }else{
                if(!map.get(username).getPassword().equals(password)){
                    msg = CodeEnum.WRONG_PASSWORD.getMsg();
                    code = CodeEnum.WRONG_PASSWORD.getCode();
                }else{
                    msg = CodeEnum.LOGIN_SUCCESSFUL.getMsg();
                    code = CodeEnum.LOGIN_SUCCESSFUL.getCode();
                }
            }
        }
        return new ResponseResult<Boolean>(msg,code,true);
    }
    //注册的方法
    public static ResponseResult register(ServletContext servletContext, User user){
        String msg = "";
        Integer code = 0;
        String username = user.getUsername();
        //获取userMap
        HashMap<String,User> userMap = (HashMap<String, User>) servletContext.getAttribute(Config.USER_MAP);
        if (StringUtil.notNullVerify(username) || StringUtil.notNullVerify(username)) {
            msg = CodeEnum.USERNAME_OR_PASSWORD_IS_EMPTY.getMsg();
            code = CodeEnum.USERNAME_OR_PASSWORD_IS_EMPTY.getCode();
        }else{
            //判断用户名是否已经存在
            if(userMap.get(username)!=null){
                msg = CodeEnum.USER_ALREADY_EXISTS.getMsg();
                code = CodeEnum.USERNAME_OR_PASSWORD_IS_EMPTY.getCode();
            }else{
                userMap.put(username,user);
                msg = CodeEnum.REGISTRATION_SUCCESS.getMsg();
                code = CodeEnum.REGISTRATION_SUCCESS.getCode();
            }
        }
        return new ResponseResult<Boolean>(msg,code,true);
    }
}
